package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.CountryDao;
import com.ubs.training.server.dao.model.Country;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 7:34 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamCountryDaoImpl implements CountryDao {
    DataSource ds;

    NamedParameterJdbcOperations ops;


    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }

    @Override
    public List<Country> getAll() {
        return ops.query("select ID, CName from countries", Collections.EMPTY_MAP, new BeanPropertyRowMapper(Country.class));
    }

    @Override
    public Country getById(int id) {
        return ops.queryForObject("select ID, CName from countries where id=:ID", Collections.singletonMap("countries", id), new BeanPropertyRowMapper<Country>(Country.class));
    }

    @Override
    public void add(Country country) {
        int id = ops.queryForInt("select next value for cmstr_seq from dual", Collections.EMPTY_MAP);
        country.setID(id);
        ops.update("insert into countries values (:ID, :CName)", new BeanPropertySqlParameterSource(country));

    }

    @Override
    public void update(Country country) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
